package com.ktjiaoyu.image.search.mcpserver.tools;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ImageSearchTool {
    // 记录日志
    private static Logger LOGGER = LoggerFactory.getLogger(ImageSearchTool.class);
    // 从配置中获取接口信息，避免接口变化需要修改源码
    @Value("${interface-box.api.image-search-url}")
    private String apiUrl;
    @Value("${interface-box.id}")
    private String id;
    @Value("${interface-box.key}")
    private String key;

    /**
     * Search for images based on keywords
     * @param keyword The keyword to search for images
     * @return A string containing information about the found images
     */
    @Tool(description = "Search for images based on keywords from Baidu image source.")
    public String searchImage(@ToolParam(description = "The keyword to search for images, e.g., '张含韵'", required = true) String keyword) {
        try {
            // 构建请求参数
            String params = String.format("id=%s&key=%s&words=%s&limit=5&page=1", 
                id, key, URLUtil.encode(keyword));
            
            LOGGER.info("Sending image search POST request to: {} with params: {}", apiUrl, params);
            
            // 使用Hutool发送HTTP POST请求
            HttpResponse response = HttpRequest.post(apiUrl)
                    .body(params)
                    .contentType("application/x-www-form-urlencoded")
                    .timeout(10000) // 设置超时时间10秒
                    .execute();
            
            // 获取响应内容
            String result = response.body();
            LOGGER.info("Received response from image search API: {}", result);
            
            // 检查响应是否为有效的JSON格式
            if (!JSONUtil.isTypeJSON(result)) {
                LOGGER.error("Invalid JSON response from image search API: {}", result);
                return "Error: Invalid response format from image search API.";
            }
            
            // 解析JSON响应
            JSONObject jsonObject = JSONUtil.parseObj(result);
            
            // 检查API返回的状态码
            Integer code = jsonObject.getInt("code");
            if (code == null || code != 200) {
                String errorMsg = jsonObject.getStr("msg", "Unknown error");
                LOGGER.error("Image search API returned error: {}", errorMsg);
                return "Error occurred during image search: " + errorMsg;
            }
            
            // 提取图片结果
            JSONArray images = jsonObject.getJSONArray("res");
            if (images == null || images.isEmpty()) {
                return "No images found for keyword: " + keyword;
            }
            
            // 构建返回结果字符串
            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.append("Found ")
                    .append(images.size())
                    .append(" images for keyword '")
                    .append(keyword).append("':\n");
            
            // 添加前5张图片的URL（或所有图片，如果少于5张）
            int count = 0;
            for (Object imageObj : images) {
                if (count >= 5) break; // 限制返回前5张图片
                resultBuilder.append((count + 1)).append(". ").append(imageObj.toString()).append("\n");
                count++;
            }
            
            return resultBuilder.toString();
        } catch (Exception e) {
            LOGGER.error("Exception occurred during image search: ", e);
            return "Error occurred during image search: " + e.getMessage();
        }
    }
}